package org.yjc.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.DatagridUtils;
import org.yjc.custom.JournalUtils;
import org.yjc.custom.UserUtils;
import org.yjc.entity.College;
import org.yjc.entity.Student;
import org.yjc.entity.SysRole;
import org.yjc.entity.SysUser;
import org.yjc.entity.Teacher;
import org.yjc.form.StudentForm;
import org.yjc.form.TeacherForm;
import org.yjc.repository.SysRoleRepository;
import org.yjc.service.CollegeService;
import org.yjc.service.SysUserService;
import org.yjc.service.TeacherService;

@Controller
@RequestMapping(value="/teacher")
public class TeacherController {
	@Autowired
	private TeacherService teacherservice;
	@Autowired
	private CollegeService collegeservice;
	@Autowired
	private SysRoleRepository roleDAO;
	@Autowired
	private UserUtils userutils;
	@Autowired
	private JournalUtils journalutils;
	@Autowired
	private SysUserService sysuserservice;
	
	@RequestMapping(value="/teachermain")
	public String teachermain(ModelMap map) {
		List<College> college = collegeservice.findAll();
		map.put("college", college);
		return "teacher/teachermain";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(DatagridUtils param,String name,String username,String age,String collegeid) {
		Pageable pageable = param.buildPageable();
		Page<Teacher> page = null;
		//安全查询
		Specification<Teacher> spec = new Specification<Teacher>() {
			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(name)) {
					rules.add(criteriaBuilder.like(root.get("name"), "%"+name+"%"));
				}else if(StringUtils.hasText(username)) {
					rules.add(criteriaBuilder.like(root.get("username"), "%"+username+"%"));
				}else if(StringUtils.hasText(age)) {
					rules.add(criteriaBuilder.like(root.get("age"), "%"+age+"%"));
				}
				rules.add(criteriaBuilder.equal(root.get("college").get("id"),collegeid));
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		page = teacherservice.findAll(spec,pageable);
		HashMap<String, Object> result = DatagridUtils.biuldDatagridResult(page);
		return result;
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public String save(TeacherForm form,Integer collegeid) {
		SysUser sysuser = userutils.getUser(); //获取到当前用户
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		Teacher teacher = new Teacher();
		if(form.getId()!=null) {
			teacher = teacherservice.findById(form.getId());
			teacher.setId(form.getId());
			BeanUtils.copyProperties(form, teacher);
			//录入日志
			journalutils.journal1("修改教师信息",sysuser.getName()+"进行了修改教师信息操作");
		}else {
			BeanUtils.copyProperties(form, teacher,"id");
			journalutils.journal1("添加教师",sysuser.getName()+"添加了"+"("+form.getName()+")");
		}
		teacher.setPassword(encoder.encode("111111")); //把密码进行加密
		teacher.setCollege(collegeservice.findById(collegeid)); //存入学院
		SysRole role = roleDAO.findById(3).get(); //给权限
		teacher.getRoles().add(role);
		teacherservice.save(teacher);
		return "OK";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public String delete(String ids) {
		SysUser sysuser = userutils.getUser();
		String[] ids1 = ids.split(",");//去除“，” 将多个id存入数组中
		for(int i = 0;i<ids1.length;i++) {
			Teacher teacher = teacherservice.findById(Integer.parseInt(ids1[i]));
			teacherservice.deleteById(Integer.parseInt(ids1[i]));
			//日志
			journalutils.journal1("删除学生",sysuser.getName()+"删除了"+"("+teacher.getName()+")");
		}
		return "OK";
	}
	
	@RequestMapping(value="/reload")
	@ResponseBody
	public String reload(String ids) {
		SysUser sysuser = userutils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		String[] ids1 = ids.split(",");//去除“，” 将多个id存入数组中
		for(int i = 0;i<ids1.length;i++) {
			Teacher teacher = teacherservice.findById(Integer.parseInt(ids1[i]));
			teacher.setPassword(encoder.encode("111111"));
			teacherservice.save(teacher);
			//日志
			journalutils.journal1("重置教师密码",sysuser.getName()+"重置了"+"("+teacher.getName()+")的密码");
		}
		return "OK";
	}
	
	@RequestMapping(value="/message1")
	public String message1(ModelMap map) {
		Integer id = userutils.getUser().getId();
		Teacher teacher = teacherservice.findById(id);
		SysRole role = roleDAO.findById(3).get(); //给权限
		map.put("role", role);
		map.put("teacher", teacher);
		return "teacher/message1";
	}
}
